using System;
using System.Net;
using System.Collections;

namespace ActorSystem
{
	public class Control
	{
		private ArrayList ActorsById;
		private ArrayList Actors;
		private ControlServer localControlServer;
		
		public Control() 
		{
			ActorsById = new ArrayList();
			Actors = new ArrayList();
			this.localControlServer = new ControlServer(this);
		}
		
		//Class to control the actors. Control the communication and creation of new actors
		public void Send(Id to, Id from, Object content) 
		{
			//Send the message content to "to"
			Message msg = new Message(to, from, content);
			localControlServer.SendMessage(msg);
		}
		
		public void RecieveMessage(Message msg)
		{
			//Got message
			//Give it to the right actor
			foreach (Actor a in Actors)
			{
				if (a.LocalId.ActorIdentifier == msg.To.ActorIdentifier)
				{
					a.AddMessage(msg);
					break;
				}
			}
		}

        public Actor CreateActor(Type type)
        {
            Actor res = (Actor)Activator.CreateInstance(type);
            res.LocalControl = this;
            res.CreateId();
            ActorsById.Add(res.LocalId);
            Actors.Add(res);
            return res;
        }

		public Actor CreateActor(string className)
		{
			//Create a new actor on the node, with the lowest load
			//This should be en a function for itself
			Actor res = (Actor)Activator.CreateInstance(Type.GetType(className));
			res.LocalControl = this;
			res.CreateId();
			ActorsById.Add(res.LocalId);
			Actors.Add(res);
			return res;
		}
		
		public void UpdateNodes()
		{
			//Update the nodes in the system
			//Broadcast a message
			
		}
		
		public IPAddress GetHostIp() 
		{
			string myHost = Dns.GetHostName();
			IPAddress[] myIPs = Dns.GetHostAddresses(myHost);
			return myIPs[0];
		}
	}
}